<template>
  <div class="hedge-rule layout-content">
    <div class="hedgeCategory">
      <p>
        <a-alert
          show-icon
          type="warning"
          message="自动套保只对已设置了的套保品种进行自动套保，新增/编辑/删除套保品种，需要等待期货休盘之后才生效。"
        >
        </a-alert>
      </p>
      <c-table
        :data="ruleList"
        :columns="ruleColumns"
        :loading="tableLoading"
        :add="$btn('addRule')"
        addText="新增套保品种策略"
        expanded
        @onAdd="addCategoryConfig"
        @onReload="reload"
      >
        <template v-slot:expanded="{ row }">
          <c-desc :data="row" :column="2" :columns="expandedColumns">
            <template v-slot:openingRule>
              <span>{{
                $getEnum(hedgeDict.openingRule, row.openingRule)
              }}</span>
            </template>
            <template v-slot:closingRule>
              <span>{{
                $getEnum(hedgeDict.closingRule, row.closingRule)
              }}</span>
            </template>
            <template v-slot:deliveryRule>
              <a-tag color="orange">策略{{ row.deliveryRule }}</a-tag
              ><span>{{
                $getEnum(hedgeDict.deliveryRule, row.deliveryRule)
              }}</span>
            </template>
          </c-desc>
        </template>
        <template v-slot:header-l>
          <c-button type="success" @click="enableAll" v-if="$btn('enableAll')"
            >全部启用</c-button
          >
          <c-button type="danger" @click="disableAll" v-if="$btn('disableAll')"
            >全部停用</c-button
          >
        </template>
        <template v-slot:hedgeConfigStatus="{ row }">
          <a-tag :color="hedgeConfigStatusColor(row)">{{
            $getEnum(hedgeDict.configStatus, row)
          }}</a-tag>
        </template>
        <template v-slot:scale>
          100%
        </template>
        <template v-slot:handle="{ row }">
          <div class="handle">
            <template v-for="i in handleBtns(row)">
              <c-button
                type="link"
                :key="i.title"
                @click="i.clickEvent(row)"
                v-if="!i.hidden"
                >{{ i.title }}</c-button
              >
            </template>
          </div>
        </template>
      </c-table>
    </div>
  </div>
</template>

<script>
import {
  getcompanyhedgeconfiglist,
  deleteconfig,
  disableconig,
  enableconfig,
  freezeconfig,
  enableallconfig,
  disableallconfig
} from "@/api/hedge";
import hedgeDict from "@/dict/hedge";

const expandedColumns = [
  {
    label: "开仓策略",
    slot: "openingRule"
  },
  {
    label: "平仓策略",
    slot: "closingRule"
  },
  {
    label: "交割月策略",
    span: 2,
    slot: "deliveryRule"
  }
];

const ruleColumns = [
  {
    title: "套保品种",
    dataIndex: "categoryName"
  },
  {
    title: "对应套保比例",
    dataIndex: "scale",
    scopedSlots: { customRender: "scale" }
  },
  {
    title: "套保账户",
    dataIndex: "hedgeAccountName"
  },
  {
    title: "状态",
    dataIndex: "hedgeConfigStatus",
    scopedSlots: { customRender: "hedgeConfigStatus" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "handle" }
  }
];

export default {
  data() {
    return {
      hedgeDict,
      hedgeSwitch: false,
      tableLoading: false,
      ruleList: [],
      ruleColumns,
      expandedColumns,
      filterCategorys: [] // 新增时需要过滤的品种
    };
  },
  computed: {
    // 配置状态颜色
    hedgeConfigStatusColor() {
      return row => {
        let c =
          row === this.hedgeDict.configStatus.enable.value
            ? "green"
            : row === this.hedgeDict.configStatus.disable.value
            ? "red"
            : "";
        return c;
      };
    },
    // 操作按钮
    handleBtns() {
      return row => {
        let res = [
          {
            title: "编辑策略",
            clickEvent: this.edit,
            hidden: this.$btn("editRule") ? false : true
          },
          {
            title: "启用",
            clickEvent: this.enable,
            hidden:
              [
                this.hedgeDict.configStatus.disable.value,
                this.hedgeDict.configStatus.freeze.value
              ].indexOf(row.hedgeConfigStatus) === -1 && !this.$btn("enable")
                ? true
                : false
          },
          {
            title: "停用",
            clickEvent: this.disable,
            hidden:
              row.hedgeConfigStatus !==
                this.hedgeDict.configStatus.enable.value &&
              !this.$btn("disable")
          },
          {
            title: "冻结",
            clickEvent: this.freeze,
            hidden:
              row.hedgeConfigStatus !==
                this.hedgeDict.configStatus.enable.value && !this.$btn("freeze")
          },
          {
            title: "删除",
            clickEvent: this.del,
            hidden: this.$btn("delHedgeRule") ? false : true
          }
        ];
        return res;
      };
    }
  },
  methods: {
    // 删除配置
    del(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: `是否确认删除套保品种：${row.categoryName} ？删除套保品种，需要等待期货休盘后才生效。`,
        onOk() {
          return new Promise((resolve, reject) => {
            deleteconfig({
              id: row.id
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 冻结配置
    freeze(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: `是否确认冻结套保品种：${row.categoryName} ？`,
        onOk() {
          return new Promise((resolve, reject) => {
            freezeconfig({
              id: row.id
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 停用配置
    disable(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: `是否确认停用套保品种：${row.categoryName} ？`,
        onOk() {
          return new Promise((resolve, reject) => {
            disableconig({
              id: row.id
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 全部停用
    disableAll() {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: `是否全局停用套保品种规则状态？如果确定，处于正常的状态都会将变成失效状态。冻结状态不做处理`,
        onOk() {
          return new Promise((resolve, reject) => {
            disableallconfig()
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 启用配置
    enable(row) {
      enableconfig({
        id: row.id
      }).then(() => {
        this.$message.success("操作成功");
        this.reload();
      });
    },
    // 全部启用
    enableAll() {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: `是否全局启用套保品种规则状态？如果确定，处于失效的状态都会将变成正常状态。冻结状态不做处理`,
        onOk() {
          return new Promise((resolve, reject) => {
            enableallconfig()
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 编辑策略
    edit(row) {
      this.$router.push({
        name: "hedgeStrategyUpdate",
        query: { id: row.id }
        // params: { ...row, filterCategorys: this.filterCategorys }
      });
    },
    // 添加套保品种策略
    addCategoryConfig() {
      this.$router.push({
        name: "hedgeStrategyAdd",
        params: { filterCategorys: this.filterCategorys }
      });
    },
    // 刷新列表
    reload() {
      this.getHedgeConfigList();
    },
    // 点击套保开关
    clickHedgeSwitch() {
      let _this = this;
      this.switchVisible = true;
      this.$confirm({
        title: "温馨提示",
        content:
          "是否全局控制套保品种规则状态？如果确定，处于正常的状态都会将变成失效状态。",
        onOk() {
          return new Promise(resolve => {
            _this.hedgeSwitch = !_this.hedgeSwitch;
            resolve();
          });
        }
      });
    },
    // 获取套保配置列表
    getHedgeConfigList() {
      this.tableLoading = true;
      getcompanyhedgeconfiglist()
        .then(res => {
          if (res) {
            this.ruleList = res;
            // 记录已有的品种，用于新增时过滤
            this.filterCategorys = res.map(i => i.categoryName);
          } else {
            this.ruleList = [];
            this.filterCategorys = [];
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    }
  },
  created() {
    this.getHedgeConfigList();
  }
};
</script>

<style lang="scss" scoped>
.hedgeSwitch {
  margin-bottom: 20px;
}
.hedgeSwitchWrapper {
  position: relative;
  .mask {
    position: absolute;
    top: 1px;
    left: 1px;
    width: 44px;
    height: 22px;
  }
}
</style>
